import requests
import json
from read_search_file import  return_headers, return_post_headers, return_content_type_post_headers
from DataRecorder import Recorder

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)
def collect_star_info(cookies=None, star_id=None, r=None, log_callback=None):
    star_info_url = f"https://pgy.xiaohongshu.com/api/solar/cooperator/user/blogger/{star_id}"

    headers = return_headers(star_id=star_id)
    response = requests.get(url=star_info_url, headers=headers, cookies=cookies)
    res_json = response.json()
    if res_json.get('code') == 0:
        res_data = res_json.get('data')
        combined_tags = auth_tag(res_data)

        r.update({
            '达人昵称': res_data.get('name', ''),
            '博主ID': res_data.get('redId', ''),
            '是否行业推荐': {1: '优质博主', 2: '无', 3: '新锐博主', 4: '行业推荐'}.get(res_data.get('kolHeadLabel'), '无'),
            '博主性别': res_data.get('gender', '未知'),
            '粉丝数': res_data.get('fansNum', '未知'),
            '赞藏数': res_data.get('likeCollectCountInfo', 0),
            '机构': res_data.get('noteSign', {}).get('name') if res_data.get('noteSign') is not None else '无机构',
            '作者标签': ','.join(combined_tags),
            '蒲公英链接': f'https://pgy.xiaohongshu.com/solar/pre-trade/blogger-detail/{star_id}?isFromLive=true',
            '主页链接': f'https://www.xiaohongshu.com/user/profile/{star_id}',
            '博主Base地': res_data.get('location', ''),
            '图文报价': res_data.get('picturePrice', ''),
            '视频报价': res_data.get('videoPrice', ''),
        })
        log_message(log_callback, f'达人ID基本信息:{star_id}获取成功', "green")
        collect_day_note_info(cookies=cookies, star_id=star_id, r=r, log_callback=log_callback)  #获取日常笔记基本信息
    else:
        log_message(log_callback, f'达人ID基本信息:{star_id}获取失败', "red")


def collect_day_note_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/pgy/kol/data/data_summary"
    headers = return_headers(star_id=star_id)

    params = {
        "userId": star_id,
        "business": "0"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        r.update({
            '曝光中位数(日常)': res_data.get('mAccumImpNum', ''),
            '阅读中位数（日常）': res_data.get('readMedian', ''),
            '互动中位数（日常）': res_data.get('mEngagementNum', ''),
        })
        log_message(log_callback, f'达人ID日常笔记信息:{star_id}获取成功', "green")
    else:
        log_message(log_callback, f'达人ID日常笔记信息:{star_id}获取失败', "red")


def collect_coope_note_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/pgy/kol/data/data_summary"
    headers = return_headers(star_id=star_id)

    params = {
        "userId": star_id,
        "business": "1"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        r.update({
            '曝光中位数(合作)': res_data.get('mAccumImpNum', ''),
            '阅读中位数（合作）': res_data.get('readMedian', ''),
            '互动中位数（合作）': res_data.get('mEngagementNum', ''),
            '预估CPM(图文)': round(float(res_data.get('estimatePictureCpm', 0)), 2),
            '预估CPM(视频)': round(float(res_data.get('estimateVideoCpm', 0)), 2),
            '预估阅读单价(图文)': round(float(res_data.get('picReadCost', 0)), 2),
            '预估阅读单价(视频)': round(float(res_data.get('videoReadCostV2', 0)), 2),
        })
        log_message(log_callback, f'达人ID合作笔记信息:{star_id}获取成功', "green")
    else:
        log_message(log_callback, f'达人ID合作笔记信息:{star_id}获取失败', "red")


def collect_traffic_source_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/solar/kol/data_v3/notes_rate"
    headers = return_headers(star_id=star_id)

    params = {
        "userId": star_id,
        "business": "0",
        "noteType": "3",
        "dateType": "1",
        "advertiseSwitch": "1"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        pagePercent = res_data.get('pagePercentVo', {})
        if pagePercent is not None:
            r.update({
                '近期流量来源-阅读量来源-发现页': f'{round(float(pagePercent.get("readHomefeedPercent", 0)), 4) * 100}%',
                '近期流量来源-阅读量来源-搜索页': f'{round(float(pagePercent.get("readSearchPercent", 0)), 4) * 100}%',
                '近期流量来源-阅读量来源-关注页': f'{round(float(pagePercent.get("readFollowPercent", 0)), 4) * 100}%',
                '近期流量来源-阅读量来源-博主个人页': f'{round(float(pagePercent.get("readDetailPercent", 0)), 4) * 100}%',
                '近期流量来源-阅读量来源-附近页': f'{round(float(pagePercent.get("readNearbyPercent", 0)), 4) * 100}%',
                '近期流量来源-阅读量来源-其他': f'{round(float(pagePercent.get("readOtherPercent", 0)), 4) * 100}%',

                '近期流量来源-曝光量来源-发现页': f'{round(float(pagePercent.get("impHomefeedPercent", 0)), 4) * 100}%',
                '近期流量来源-曝光量来源-搜索页': f'{round(float(pagePercent.get("impSearchPercent", 0)), 4) * 100}%',
                '近期流量来源-曝光量来源-关注页': f'{round(float(pagePercent.get("impFollowPercent", 0)), 4) * 100}%',
                '近期流量来源-曝光量来源-博主个人页': f'{round(float(pagePercent.get("impDetailPercent", 0)), 4) * 100}%',
                '近期流量来源-曝光量来源-附近页': f'{round(float(pagePercent.get("impNearbyPercent", 0)), 4) * 100}%',
                '近期流量来源-曝光量来源-其他': f'{round(float(pagePercent.get("impOtherPercent", 0)), 4) * 100}%',
            })
            log_message(log_callback, f'达人ID近期流量来源信息:{star_id}获取成功', "green")
    else:
        log_message(log_callback, f'达人ID近期流量来源信息:{star_id}获取失败', "red")



def collect_detail_source_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/solar/kol/data_v3/notes_rate"
    headers = return_headers(star_id=star_id)

    params = {
        "userId": star_id,
        "business": "1",
        "noteType": "3",
        "dateType": "1",
        "advertiseSwitch": "1"
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        if res_data is not None:
            r.update({
                '粉丝互动率': f'{res_data.get("interactionRate", 0)}%',
                '视频完播率': f'{res_data.get("videoFullViewRate", 0)}%',
                '千赞笔记比例': f'{res_data.get("thousandLikePercent", 0)}%',
                '百赞笔记比例': f'{res_data.get("hundredLikePercent", 0)}%',
            })
            log_message(log_callback, f'达人ID - {star_id} 粉丝互动率、视频完播率、千赞笔记比例、百赞笔记比例获取成功', "green")
    else:
        log_message(log_callback, f'达人ID - {star_id} 粉丝互动率、视频完播率、千赞笔记比例、百赞笔记比例获取失败', "red")


def collect_waiyi_source_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/pgy/kol/data/core_data"
    headers = return_content_type_post_headers(star_id=star_id)

    data = {
        "userId": star_id,
        "business": 1,
        "noteType": 3,
        "dateType": 1,
        "advertiseSwitch": 1
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=cookies, data=data)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        if res_data is not None:
            # 获取 cpuv 并做安全转换
            cpuv_value = res_data.get("sumData", {}).get("cpuv")
            try:
                cpuv_float = round(float(cpuv_value), 2) if cpuv_value is not None else 0.0
            except (ValueError, TypeError):
                cpuv_float = 0.0  # 如果值不能转成数字，默认设为 0.0

            r.update({
                '外溢进店单价': f'{cpuv_float}',
            })
            log_message(log_callback, f'达人ID外溢信息:{star_id}获取成功', "green")
    else:
        log_message(log_callback, f'达人ID外溢信息:{star_id}获取失败', "red")


def collect_fans_summary_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = "https://pgy.xiaohongshu.com/api/solar/kol/data_v3/fans_summary"
    headers = return_headers(star_id=star_id)

    params = {
        "userId": star_id
    }
    response = requests.get(url, headers=headers, cookies=cookies, params=params)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        if res_data is not None:
            r.update({
                '粉丝增量': f'{res_data.get("fansIncreaseNum", "")}',
                '活跃粉丝占比': f'{res_data.get("activeFansRate", "")}%',
                '下单粉丝占比': f'{res_data.get("payFansUserRate30d", "")}%',
            })
            log_message(log_callback, f'达人ID - {star_id} - 粉丝信息-粉丝增量，活跃粉丝占比，下单粉丝占比:获取成功', "green")
    else:
        log_message(log_callback, f'达人ID - {star_id} - 粉丝信息-粉丝增量，活跃粉丝占比，下单粉丝占比:获取失败', "red")

def collect_fans_profile_info(cookies=None, star_id=None, r=None, log_callback=None):
    url = f"https://pgy.xiaohongshu.com/api/solar/kol/data/{star_id}/fans_profile"
    headers = return_headers(star_id=star_id)

    response = requests.get(url, headers=headers, cookies=cookies)
    res_json = response.json()

    if res_json.get('code') == 0:
        res_data = res_json.get('data')

        if res_data is not None:
            # 提取年龄分布
            age_list = res_data.get('ages', [])
            for item in age_list:
                group = item['group']
                percent = f"{round(item['percent'] * 100, 2)}%"
                r.update({f'年龄:{group}占比': percent})

            # 提取性别分布 - 女性占比
            gender_dict = res_data.get('gender', {})
            female_ratio = f"{round(gender_dict.get('female', 0) * 100, 2)}%"
            r.update({'女粉丝占比': female_ratio})

            # 提取城市 TOP3
            city_list = res_data.get('cities', [])
            top_3_cities = city_list[:3]
            city_str = ' , '.join([f"{city['name']} {round(city['percent'] * 100, 2)}%" for city in top_3_cities])
            r.update({'粉丝base地前三': city_str})
            log_message(log_callback, f'达人ID - {star_id} - 粉丝分布详情信息:获取成功', "green")
    else:
        log_message(log_callback, f'达人ID - {star_id} - 粉丝分布详情信息:获取失败', "red")



def auth_tag(res_data):
    content_tags = res_data.get('contentTags') or []
    feature_tags = res_data.get('featureTags') or []
    # 只提取 contentTags 中的 taxonomy1Tag
    content_tag_list = [
        tag.get('taxonomy1Tag', '') for tag in content_tags
    ]
    # 合并 content_tag_list 和 feature_tags
    combined_tags = content_tag_list + feature_tags
    return combined_tags